package com.maxiaoke.boot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传测试
 */
@Slf4j
@Controller
public class FormController {

    @GetMapping("/form_layouts")
    public String form_layouts() {

        return "form/form_layouts";
    }

    @PostMapping("/upload")
    public String upload(
            @RequestParam("email") String email,
            @RequestParam("name") String name,
            @RequestPart("avatar") MultipartFile avatar,
            @RequestPart("photos") MultipartFile[] photos
    ) throws IOException {

        log.info("上传的信息是: email={}, name={},avatar={},photos={}",
                email, name, avatar.getSize(), photos.length);


        //单个文件上传
        if (!avatar.isEmpty()) {
            //保存到文件服务器，或oss服务器
            String originalFileName = avatar.getOriginalFilename();
            avatar.transferTo(new File("F:\\fileupload\\" + originalFileName));
        }

        //多个文件上传
        if (photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("F:\\fileupload\\" + originalFilename));

                }
            }
        }

        return "main";
    }


}
